<template>
	<NavBar title="发布商品"/>
	<view class="release-goods">
		<uni-forms ref="formRef" :rules="rules" :model="goodsInfo">
			<view class="goods-info">
				<uni-forms-item name="name">
					<view class="item">
						<view class="label"> 名称 </view>
						<uni-easyinput class="easy-input" v-model="goodsInfo.name" placeholder="请输入产品名称" placeholderStyle="color: #D8D8D8;" :input-border="false" :clearable="false" />
					</view>
				</uni-forms-item>
        <uni-forms-item name="category_id">
        	<view class="item">
        		<view class="label"> 平台分类 </view>
        		<view class="value" @tap="openModal(1)">
        			<view class="text" :class="categoryPName?'a-text':''"> {{categoryPName?categoryPName:'请选择平台分类'}} </view>
        			<image src="/static/icon/order/right.png" class="right"/>
        		</view>
        	</view>
        </uni-forms-item>
				<uni-forms-item name="category_id">
					<view class="item">
						<view class="label"> 类别 </view>
						<view class="value" @tap="openModal(2)">
							<view class="text" :class="categoryName?'a-text':''"> {{categoryName?categoryName:'请选择商品类别'}} </view>
							<image src="/static/icon/order/right.png" class="right"/>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item name="restrict_num">
					<view class="item">
						<view class="label"> 起售数量 </view>
						<uni-easyinput type="number" class="easy-input" v-model="goodsInfo.restrict_num" placeholder="多少份起卖，0表示不限购" placeholderStyle="color: #D8D8D8;" :input-border="false" :clearable="false" />
					</view>
				</uni-forms-item>
				<uni-forms-item name="restrict_num_max">
					<view class="item">
						<view class="label"> 每单限购 </view>
						<uni-easyinput type="number" class="easy-input" v-model="goodsInfo.restrict_num_max" placeholder="每单最多可购买份量，0表示不限购" placeholderStyle="color: #D8D8D8;" :input-border="false" :clearable="false" />
					</view>
				</uni-forms-item>
				<uni-forms-item name="dabao_money">
					<view class="item">
						<view class="label"> 其他费用 </view>
						<uni-easyinput type="number" class="easy-input" v-model="goodsInfo.dabao_money" placeholder="请填写其他费用" placeholderStyle="color: #D8D8D8;" :input-border="false" :clearable="false" />
					</view>
				</uni-forms-item>
				<uni-forms-item name="sort">
					<view class="item">
						<view class="label"> 序号 </view>
						<uni-easyinput type="number" class="easy-input" v-model="goodsInfo.sort" placeholder="用于排序，越大越靠前" placeholderStyle="color: #D8D8D8;" :input-border="false" :clearable="false" />
					</view>
				</uni-forms-item>
			</view>
			<view class="shop-desc">
				<uni-forms-item name="msg">
					<view class="title"> 描述 </view>
					<textarea 
						v-model="goodsInfo.msg"
						placeholder="设置为空时，前台则不显示，输入简单介绍"
						placeholder-style="font-size: 14px;color: #C4C4C4;"
					/>
				</uni-forms-item>	
			</view>
			<view class="goods-chart">
				<uni-forms-item name="img">
					<view class="title"> 主图 </view>
					<view class="img-box">
						<ChooseBtn @choose="chooseImg" v-if="imgUrl==''" />
						<view class="img" v-else>
							<image :src="imgUrl" class="chart" @tap="previewImg([imgUrl])"/>
							<image src="/static/icon/shop/close-img.png" class="close" @tap="delImgOrVideo('img')" />
						</view>
					</view>
					<view class="tips"> 支持jpg格式 </view>
				</uni-forms-item>	
			</view>
			<view class="goods-video">
				<uni-forms-item name="imgs">
					<view class="title"> 轮播图(3-5)张 </view>
					<view class="img-box">
						<ChooseBtn @choose="chooseImgs" v-if="imgsUrl.length!=5" />
						<view class="img" v-if="imgsUrl.length" v-for="(item, i) in imgsUrl" :key="item">
							<image :src="item" class="chart" @tap="previewImg(imgsUrl)"/>
							<image src="/static/icon/shop/close-img.png" class="close" @tap="delImgs(i)" />
						</view>
					</view>
					<view class="tips"> 支持jpg格式 </view>
				</uni-forms-item>	
			</view>
			<view class="goods-video">
				<uni-forms-item name="video">
					<view class="title"> 视频 </view>
					<view class="img-box">
						<ChooseBtn fileType="video" @choose="chooseVideo" v-if="videoUrl == ''" />
						<view class="img" v-else>
              <image src="/static/icon/video.png" class="video" @tap="viewVideo"/>
							<image src="/static/icon/shop/close-img.png" class="close" @tap="delImgOrVideo('video')" />
						</view>
					</view>
					<view class="tips"> 视频必须为mp4格式 </view>
				</uni-forms-item>	
			</view>
			<AddSpec ref="speceRef" />
			<view class="goods-desc">
				<uni-forms-item name="detail">
					<view class="title"> 详情 </view>
          <Editor @exportEditor="exportEditor"/>
					<!-- <textarea v-model="goodsInfo.detail" placeholder="设置为空时，前台则不显示，输入详情介绍" /> -->
				</uni-forms-item>	
			</view>
			<view class="goods-status">
				<view class="item">
					<view class="label"> 状态 </view>
					<view class="value" @tap="goodsStatusRef.open()">
						<text>{{activeName}}</text>
						<image src="/static/icon/order/right.png" class="v-img"/> 
					</view>
				</view>
				<uni-forms-item name="start_time">
					<view class="item">
						<view class="label"> 设置时间 </view>
						<view class="value" @tap="selectTimeRef.open()">
							<text>{{goodsInfo.start_time}}-{{goodsInfo.over_time}}</text>
							<image src="/static/icon/order/right.png"  class="v-img"/> 
						</view>
					</view>
				</uni-forms-item>	
			</view>
			<view class="goods-keyword">
				<uni-forms-item name="label">
          <!--  @tap="getKeyWord" -->
					<view class="title">
						<view class="name"> 搜索关键词添加 </view>
					</view>
					<view class="keyword-box">
						<view class="keyword-item" v-for="(item, i) in keyWordList" :key="item">
              {{item}}
              <view class="del-key"> <uni-icons type="minus-filled" color="#FF3B1E" @tap="delKeyWords(i)"/> </view>
            </view>
            <div class="add-key" @tap="modalRef.open()" v-if="keyWordList.length<5"> 添加 </div>
					</view>
					<view class="num"> {{keyWordList.length}}/5 </view>
				</uni-forms-item>	
			</view>
		</uni-forms>
		<view class="btn-box">
			<view class="btn" @tap="submit"> 确定 </view>
		</view>
		<SelStatus ref="goodsStatusRef" :arr="['上架', '下架']" @selected="selGoodsStatus" />
		<SelTime ref="selectTimeRef" @selectedTime="selectedTime" />
		<Picker :arr="categoryList" ref="pickerRef" @selected="pickCategory"/>
    <uni-popup ref="videoRef" type="center" @maskClick="isShowVideo = false">
      <video :src="videoUrl" v-if="isShowVideo" autoplay></video>
    </uni-popup>
    <Modal ref="modalRef" input="请输入关键词" @confirm="addKeyWords"/>
	</view>
</template>

<script setup>
	import AddSpec from './components/AddSpec.vue'
	import { ref, computed, onUnmounted } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import NavBar from '@/components/NavBar.vue'
	import SelTime from '@/components/SelectTime.vue'
	import SelStatus from '@/components/BottomSelectPopup.vue'
	import ChooseBtn from '@/components/ChooseBtn.vue'
	import Picker from '@/components/Picker.vue'
  import Editor from '@/components/Editor.vue'
  import Modal from '@/components/Modal.vue'
	import { useShopStore, useMiddleWare } from '@/store/index.js'
	import { isNull, isMobile } from '@/utils/valdate.js'
	import { GetGoodsCategoryApi, AddGoodsApi } from '@/service/shop.js'
  import { previewImg } from '@/utils/index.js'
  const modalRef = ref()
  const videoRef = ref()
  const isShowVideo = ref(true)
	const formRef = ref()
	const speceRef = ref()
	const pickerRef = ref()
	const selectTimeRef = ref()
	const goodsStatusRef = ref()
	const categoryList = ref([]) // 分类列表
	const goodsInfo = ref({
		name: "", //商品名称
		category_id: "", //规格ID
    category_id_p: "",
		show_num: "",
		restrict_num: '', //起售数量
		restrict_num_max: '', //每单限购
		dabao_money: '', //打包费
		express_money: '', //快递费(UI上没有需要加上)
		sort: '', //序号
		msg: "", //商品描述
		img: '', //商品主图
		imgs: '', //商品轮播图"992,835,790"
		video: '', //视频
		detail: "", //商品详情(富文本形式)
		active: 1, //状态 1=上架 0 =下架
		label: "", //关键词 关键字1,关键字2,关键词3
		sku_details: { //商品规格
			goods_spece: {},
			item: [{
				name: "",
				price: '',
				original_price: '',
				stock: "",
				thumb: '',
				spece_name: "",
				spece_value_name: ""
			}]
		},
		start_time: '',
		over_time: ''
	})
	const imgUrl = ref('') // 此字段仅供展示 商品主图
	const videoUrl = ref('') // 此字段仅供展示 商品视频
	const imgsId = ref([]) // 此字段仅供展示 商品轮播图id
	const imgsUrl = ref([]) // 此字段仅供展示 商品轮播图
	const activeName = ref('上架') // 此字段仅供展示
	const categoryName = ref('') // 此字段仅供展示
	const categoryPName = ref('') // 此字段仅供展示
	const rules = {
		name: isNull('商品名称'),
		category_id: isNull('商品类别'),
		category_id_p: isNull('平台分类'),
		// show_num: isNull('显示数量'),
		restrict_num: isNull('起售数量'),
		restrict_num_max: isNull('每单限购'),
		dabao_money: isNull('打包费'),
		sort: isNull('序号'),
		msg: isNull('商品描述'),
		img: isNull('商品主图'),
		video: isNull('商品视频'),
		detail: isNull('商品详情'),
		// label: isNull('关键词'),
		// start_time: isNull('时间')
	}
  const cateType = ref(1) // 1：平台分类；2：商品分类
  const openModal = (type) => {
    const { category, ptCategory } = useMiddleWare()
    cateType.value = type
    if(type == 1) categoryList.value = ptCategory
    else categoryList.value = category
    pickerRef.value.open()
  }
	const keyWordList = ref([])
  // 添加关键词
  const addKeyWords = (e) => {
    if(!e) return getApp().globalData.toast('请输入关键词')
    modalRef.value.close()
    keyWordList.value.push(e)
    goodsInfo.value.label = keyWordList.value.join(',')
  }
  // 删除关键词
  const delKeyWords = (i) => {
    keyWordList.value.splice(i, 1)
    goodsInfo.value.label = keyWordList.value.join(',')
  }
	// 选择商品主图
	const chooseImg = (e) => {
		imgUrl.value = e.img_url
		goodsInfo.value.img = e.id
	}
	const delImgOrVideo = (type) => {
		if(type == 'img') {
			imgUrl.value = ''
			goodsInfo.value.img = ''
		} else {
			videoUrl.value = ''
			goodsInfo.value.video = ''
		}
 	}
	// 选择商品轮播图
	const chooseImgs = (e) => {
		imgsId.value.push(e.id)
		imgsUrl.value.push(e.img_url)
		goodsInfo.value.imgs = imgsId.value.join(',')
	}
	// 删除商品轮播图
	const delImgs = (i) => {
		imgsId.value.splice(i, 1)
		imgsUrl.value.splice(i,1)
		goodsInfo.value.imgs = imgsId.value.join(',')
	}
	// 选择视频
	const chooseVideo = (e) => {
		videoUrl.value = e.img_url
		goodsInfo.value.video = e.id
	}
  // 查看视频
  const viewVideo = () => {
    isShowVideo.value = true
    videoRef.value.open()
  }
  // 编辑商品详情
  const exportEditor = (e) => {
    if(e == '<p><br></p>') return getApp().globalData.toast('请输入商品详情')
    const url = import.meta.env.VITE_APP_BASE_URL
    goodsInfo.value.detail = e.split(url).join('')
    // console.log(goodsInfo.value.detail, 'goodsInfo.value.detail');
  }
	// 选择商品状态 1=上架 0 =下架
	const selGoodsStatus = (e) => {
		activeName.value = e
		if(e =='上架') {
			goodsInfo.value.active = 1
		} else {
			goodsInfo.value.active = 0
		}
		goodsStatusRef.value.close()
	}
	// 选择时间
	const selectedTime = (e) => {
		goodsInfo.value.start_time = e.split('至')[0]
		goodsInfo.value.over_time = e.split('至')[1]
		selectTimeRef.value.close()
	}
	const pickCategory = (e) => {
    if (cateType.value == 1) {
      categoryPName.value = e.title
      goodsInfo.value.category_id_p = e.id
    } else {
      goodsInfo.value.category_id = e.id
      categoryName.value = e.title
    }
		pickerRef.value.close()
	}
	const getKeyWord = () => {
		uni.navigateTo({
			url: '/pages/shopPages/shopKeyWord/shopKeyWord'
		})
	}
	const getGoodsCategoryList = () => {
		GetGoodsCategoryApi().then(res => {
			categoryList.value = res.data
		})
	}
	const submit = () => {
		if(!speceRef.value.specList) return getApp().globalData.toast('请添加商品规格')
		formRef.value.validate().then(() => {
			goodsInfo.value.sku_details.goods_spece = speceRef.value.goods_spece
			goodsInfo.value.sku_details.item = speceRef.value.specList
			let params = {
				...goodsInfo.value
			}
			AddGoodsApi(params).then(res => {
				uni.navigateBack()
			})
		})
	}
	onUnmounted(() => {
		const { SETKEYWORD } = useShopStore()
		SETKEYWORD([])
	})
	onLoad(() => {
    const { setCategory } = useMiddleWare()
		GetGoodsCategoryApi().then(res => {
      setCategory(2, res.data)
		})
	})
</script>

<style scoped lang="scss">
	.release-goods {
		padding: 10px 12px 70px;
		box-sizing: border-box;
		.goods-info {
			padding: 0 12px;
			margin-bottom: 10px;
			border-radius: 10px;
			background-color: #fff;
			.uni-forms-item {
				height: 50px;
				margin-bottom: 0;
				align-items: center;
				border-bottom: 1px solid #eeeeee;
				box-sizing: border-box;
				.item {
					height: 50px;
					display: flex;
					align-items: center;
					.label {
						color: #333333;
						font-size: 16px;
						font-weight: 400;
						margin-right: 10px;
					}
					.value {
						flex: 1;
						display: flex;
						margin-left: 10px;
						padding-right: 10px;
						align-items: center;
						justify-content: flex-end;
						.text {
							color: #D8D8D8;
							font-size: 14px;
							font-weight: 400;
							&.a-text {
								color: #333333;
							}
						}
						.right {
							width: 14px;
							height: 14px;
							margin-left: 5px;
						}
					}
					.easy-input {
						flex: 1;
						color: #D8D8D8;
						font-size: 14px;
						font-weight: 400;
						text-align: right;
						margin-left: 10px;
					}
				}
			}
			:deep(.uni-forms-item__error) {
				left: 0;
				top: 100%;
				right: 12px;
				font-size: 12px;
				text-align: right;
				padding-bottom: 3px;
				transform: translateY(-100%);
			}
			.goods-item {
				height: 50px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-bottom: 1px solid #EEEEEE;
				&:nth-last-of-type(1) {
					border-bottom: none;
				}
				.label {
					width: 64px;
					color: #333333;
					font-size: 16px;
					font-weight: 400;
				}
				.value {
					flex: 1;
					display: flex;
					align-items: center;
					justify-content: end;
					color: #D8D8D8;
					font-size: 14px;
					font-weight: 400;
					margin-left: 20px;
					text-align: right;
					.placeCss {
						color: #D8D8D8;
						font-size: 14px;
					}
					.right {
						width: 14px;
						height: 14px;
					}
				}
			}
		}
		.shop-desc {
			padding: 16px;
			border-radius: 10px;
			margin-bottom: 10px;
			background-color: #fff;
			.uni-forms-item {
				margin-bottom: 0;
			}
			.title {
				color: #333333;
				font-size: 16px;
				font-weight: 400;
				line-height: 20px;
				margin-bottom: 5px;
			}
			textarea {
				width: 100%;
				height: 120px;
				color: #333333;
				font-size: 14px;
				font-weight: 400;
				line-height: 20px;
			}
		}
		.goods-chart, .goods-video {
			border-radius: 10px;
			margin-bottom: 10px;
			background-color: #fff;
			padding: 20px 16px 11px;
			.uni-forms-item {
				margin-bottom: 0;
			}
			.title {
				color: #333333;
				font-size: 16px;
				font-weight: 400;
				line-height: 20px;
				margin-bottom: 15px;
			}
			.img-box {
				margin-bottom: 10px;
				display: grid;
				grid-gap: 20px 0;
				grid-template-columns: repeat(3, 1fr);
				.img {
					width: 74px;
					height: 74px;
					position: relative;
					display: inline-block;
					.chart, .video {
						width: 74px;
						height: 74px;
						border-radius: 10px;
            overflow: hidden;
					}
					.close {
						width: 18px;
						height: 18px;
						position: absolute;
						right: 0;
						top: 0;
					}
				}
			}
			.tips {
				color: #AAAAAA;
				font-size: 12px;
				font-weight: 400;
				line-height: 20px;
			}
		}
		.goods-desc {
			padding: 16px;
			margin: 10px 0;
			border-radius: 10px;
			background-color: #fff;
			.uni-forms-item {
				margin-bottom: 0;
			}
			.title {
				color: #333333;
				font-size: 16px;
				font-weight: 400;
				line-height: 20px;
				margin-bottom: 5px;
			}
		}
		.goods-status {
			padding: 0 12px;
			border-radius: 10px;
			margin-bottom: 10px;
			background-color: #fff;
			.item {
				height: 50px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				&:nth-of-type(1) {
					border-bottom: 1px solid #EEEEEE;
					box-sizing: border-box;
				}
				.label {
					color: #333333;
					font-size: 14px;
					font-weight: 400;
				}
				.value {
					display: flex;
					align-items: center;
					color: #666666;
					font-size: 14px;
					font-weight: 400;
					.v-img {
						width: 14px;
						height: 14px;
						margin-left: 6px;
					}
				}
			}
		}
		.goods-keyword {
			border-radius: 10px;
			padding: 0 12px 10px;
			background-color: #fff;
			.uni-forms-item {
				margin-bottom: 0;
			}
			.title {
				height: 50px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-bottom: 1px solid #EEEEEE;
				.name {
					color: #333333;
					font-size: 14px;
					font-weight: 400;
				}
        .v-img {
          width: 14px;
          height: 14px;
        }
			}
			.keyword-box {
				padding: 10px 4px 0;
				display: grid;
				gap: 10px 9px;
				grid-template-columns: repeat(4, 1fr);
				.keyword-item {
          position: relative;
					width: 100%;
					height: 24px;
					color: #555555;
					font-size: 11px;
					font-weight: 400;
					line-height: 24px;
					text-align: center;
					border: 1px solid #AAAAAA;
					box-sizing: border-box;
          .del-key {
            position: absolute;
            top: 0;
            right: 0;
            transform: translate(50%, -50%);
          }
				}
        .add-key {
          width: 100%;
          height: 24px;
          font-size: 11px;
          font-weight: 400;
          line-height: 24px;
          text-align: center;
          color: #fff;
          border-radius: 5px;
          background-color: #FF3B1E;
        }
			}
			.num {
				color: #C4C4C4;
				font-size: 14px;
				font-weight: 400;
				line-height: 20px;
				text-align: right;
			}
		}
		.btn-box {
			position: fixed;
			bottom: 0;
			left: 0px;
			right: 0px;
			padding: 0 12px 10px;
			background-color: #F4F5F7;
			.btn {
				height: 50px;
				color: #FFFFFF;
				line-height: 50px;
				text-align: center;
				background: #FF3B1E;
				border-radius: 106px 106px 106px 106px;
			}
		}
	}
  :deep(.icon-baocun) {
    color: #FF3B1E;
    &::before {
      content: '保存';
      font-weight: bold;
    }
  }
</style>
